package cn.schtwz.baseproject.di

import cn.schtwz.baseproject.MyApplication

import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.OSSConstants
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken
import com.alibaba.sdk.android.oss.common.utils.IOUtils
import org.json.JSONObject
import org.koin.dsl.module

import java.net.HttpURLConnection
import java.net.URL

const val BUCKET_NAME = "htdrp"
const val END_POINT = "http://oss-cn-hangzhou.aliyuncs.com"

//mOss.presignConstrainedObjectURL(BUCKET_NAME, url, 60)

/**
 * 阿里oss
 */
val aliOssModule = module {
    //阿里oss Provider
    single<OSSFederationCredentialProvider> {
        object : OSSFederationCredentialProvider() {
            override fun getFederationToken(): OSSFederationToken {
                val authToken: OSSFederationToken
                val authData: String
                try {
                    val stsUrl = URL("$BASE_URL/appInterface/sts/getconfig")
                    val conn = stsUrl.openConnection() as HttpURLConnection
                    conn.connectTimeout = 10000
                    val input = conn.inputStream
                    authData = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME)

                    val jsonObj = JSONObject(authData)
                    val statusCode = jsonObj.getString("code")
                    if (statusCode == "1001") {
                        val data = jsonObj.getJSONObject("data")
                        val ak = data.getString("AccessKeyId")
                        val sk = data.getString("AccessKeySecret")
                        val token = data.getString("SecurityToken")
                        val expiration = data.getString("Expiration")
                        authToken = OSSFederationToken(ak, sk, token, expiration)
                    } else {
                        val errorCode = jsonObj.getString("ErrorCode")
                        val errorMessage = jsonObj.getString("ErrorMessage")
                        throw ClientException("ErrorCode: $errorCode| ErrorMessage: $errorMessage")
                    }
                    return authToken
                } catch (e: Exception) {
                    throw ClientException(e)
                }
            }

        }
    }
    single {
        val conf = ClientConfiguration()
        conf.connectionTimeout = 15 * 1000 // 连接超时，默认15秒
        conf.socketTimeout = 15 * 1000 // socket超时，默认15秒
        conf.maxConcurrentRequest = 5 // 最大并发请求书，默认5个
        conf.maxErrorRetry = 2 // 失败后最大重试次数，默认2次
        OSSClient(MyApplication.INSTANCE, END_POINT, get(), conf)
    }
}